<template>
  <div>
    <div class="header">
      城市选择
      <div class="header-left">
        <router-link to="/"
          ><span class="iconfont icon-fanhui"></span>
        </router-link>
      </div>
    </div>

    <div class="search">
      <input
        v-model="keyword"
        type="text"
        placeholder="输入城市名或拼音"
        class="search-input"
      />
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li
          @click="handleCityClick(item.name)"
          class="search-item border-bottom"
          v-for="item of keyList"
          :key="item.id"
        >
          {{ item.name }}
        </li>
        <li class="search-item border-bottom" v-show="hasNoData">
          没有找到匹配数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CityHeader',
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: '',
      keyList: []
    }
  },
  methods: {
    handleCityClick(city) {
      this.$store.dispatch('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoData() {
      return !this.keyList.length
    }
  },
  watch: {
    // shuzu() {
    //   // eslint-disable-next-line prefer-const
    //   for (let i in this.cities) {
    //     this.keyList = this.cities[i].filter((value) => {
    //       return (
    //         value.name.indexOf(this.shuzu) !== -1 ||
    //         value.spell.indexOf(this.shuzu) !== -1
    //       )
    //     })
    //   }
    // },
    keyword() {
      if (this.keyword === '') {
        this.keyList = []
        return
      }
      const prev = []
      // eslint-disable-next-line prefer-const
      for (let i in this.cities) {
        this.cities[i].forEach((value) => {
          if (
            value.name.indexOf(this.keyword) !== -1 ||
            value.spell.indexOf(this.keyword) !== -1
          ) {
            prev.push(value)
          }
        })
      }
      this.keyList = prev
    }
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="less" scoped>
.header {
  background: #00bcd4;
  color: #fff;
  line-height: 1.1467rem;
  text-align: center;

  .header-left {
    width: 0.8533rem;
    float: left;
  }
  .icon-fanhui {
    color: #fff;
  }
}
.search {
  height: 0.8rem;
  padding: 0 0.1rem;
  box-sizing: border-box;
  background: #00bcd4;
}
.search-input {
  width: 100%;
  height: 0.62rem;

  line-height: 0.62rem;
  text-align: center;
  border-radius: 0.06rem;
  color: #666;
}
.search-content {
  z-index: 1;
  position: absolute;
  top: 1.9467rem;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: hidden;
  background: #eee;
  .search-item {
    line-height: 1rem;
    color: #666;
    padding-left: 0.2rem;
    background: #fff;
  }
}
.border-bottom {
  &:before {
    border-color: #ccc;
  }
}
</style>
